<script lang="ts" setup>
import dacxService from '@/api/dacx'
import zzjgService from '@/api/zzjg'
import { ref, onMounted, h } from 'vue'
import { ElMessage } from 'element-plus'
import { TableItem } from '@/api/common'
import dayjs from 'dayjs'
import { useMainStore } from '@/store/main'
import treeSelectAll from '@/components/tree-select-edl/treeSelect.vue'
import TreeUtilDTO from '@/utils/tree'
const mainStore = useMainStore()
// 入参
defineProps({
  optionsObj: {
    type: Object,
    default: () => ({}),
  },
})

onMounted(() => {
  zzjgService.getDwbm({ dwbm: mainStore.userInfo.dwbm }).then((res: any) => {
    organizationList.value = res.data
    const flatList = TreeUtilDTO.flatten(res.data).map((item) => {
      return { ...item, children: [] }
    })
    form.value.cbdwList = flatList.map((item) => item.dwbm)
    getTableData()
  })
})
// loading
const loading = ref<boolean>(false)
const organizationList = ref([])

// 表格数据
const tjjgData = ref<TableItem>({
  data: [],
  titles: [
    {
      label: '承办单位',
      prop: 'cbdwmc',
      width: 200,
    },
    { label: '案件数', prop: 'ajs', width: 100 },
    { label: '案卷数', prop: 'ajsl', width: 100 },
    { label: '总页数', prop: 'zys', width: 100 },
    { label: '纸质页数', prop: 'zzys', width: 100 },
    { label: '音像', prop: 'yx', width: 100 },
  ],
})
const jgxqData = ref<TableItem>({
  data: [],
  titles: [
    {
      label: '业务类别',
      prop: 'mc',
      width: 200,
    },
    { label: '案件数', prop: 'ajs', width: 100 },
    { label: '案卷数', prop: 'ajsl', width: 100 },
    { label: '总页数', prop: 'zys', width: 100 },
    { label: '纸质页数', prop: 'zzajs', width: 100 },
    { label: '音像', prop: 'yx', width: 100 },
  ],
})
const display = ref(1)
// 查询条件
const form = ref<{
  cbdwList: string[]
  sljsrq: string
  slksrq: string
}>({
  cbdwList: [],
  sljsrq: '',
  slksrq: '',
})
// 查询条件表单实例
const filterFormRef = ref()
// 归档日期
const createTime = ref()

const getTableData = () => {
  if (!form.value.cbdwList.length) return
  const params = {
    cbdwList: form.value.cbdwList,
    slksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    sljsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
  }
  loading.value = true
  dacxService
    .queryGdzzl(params)
    .then((res) => {
      if (res) {
        jgxqData.value.data = []
        tjjgData.value.data = res.data
        currentRow.value = undefined
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

const currentRow = ref<any>()
const queryJgxq = (row: any) => {
  currentRow.value = row
  const params = {
    dwbm: row.cbdwbm,
    sjlx: display.value + '',
    slksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    sljsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
  }
  loading.value = true
  dacxService
    .queryGdJgtjxq(params)
    .then((res) => {
      if (res) {
        jgxqData.value.data = res.data
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}
const displayChange = (val: number) => {
  if (val === 1) {
    jgxqData.value.titles[0].label = '业务类别'
  } else {
    jgxqData.value.titles[0].label = '案件类别'
  }
  if (currentRow.value) {
    queryJgxq(currentRow.value)
  }
}

const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: any[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = h('div', {}, ['合计'])
      return
    }
    const values = data.map((item: any) => Number(item[column.property]))
    if (!values.every((value: any) => Number.isNaN(value))) {
      sums[index] = values.reduce((prev: number, curr: number) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
    } else {
      sums[index] = 'N/A'
    }
  })

  return sums
}

// 排序
const sortChange = (obj: any) => {
  console.log(obj, 'obj.prop')
}
</script>
<template>
  <div class="container">
    <!--表单-->
    <div class="form-box">
      <el-form :model="form" ref="filterFormRef" inline label-width="100px">
        <el-form-item
          prop="cbdwList"
          label="承办单位"
          :rules="[
            {
              required: true,
              message: '必选',
            },
          ]"
        >
          <tree-select-all
            style="width: 300px"
            :multiple="true"
            v-model="form.cbdwList"
            :clearable="false"
            :isLeafNode="false"
            :check-strictly="true"
            :treeProps="{
              label: 'dwmc',
              children: 'children',
            }"
            node-key="dwbm"
            :options="organizationList"
            :show-all-selection="true"
          ></tree-select-all>
        </el-form-item>
        <el-form-item label="受理日期">
          <el-date-picker
            style="width: 240px"
            v-model="createTime"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>

        <el-form-item>
          <el-radio-group v-model="display" @change="displayChange">
            <el-radio-button label="业务类别" :value="1" />
            <el-radio-button label="案件类别" :value="2" />
          </el-radio-group>
        </el-form-item>

        <el-form-item class="search">
          <el-button type="primary" @click="getTableData">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--表格-->
    <div class="table-box" v-loading="loading">
      <el-tabs model-value="tjjg">
        <el-tab-pane label="统计结果" name="tjjg" lazy>
          <el-table
            :data="tjjgData.data"
            stripe
            border
            height="100%"
            show-summary
            :summary-method="getSummaries"
            @row-click="queryJgxq"
            @sort-change="sortChange"
          >
            <el-table-column
              v-for="column in tjjgData.titles"
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :min-width="column.width"
              :sortable="true"
              show-overflow-tooltip
              resizable
            >
              <template #default="{ row }">
                <div v-if="column.custom">
                  <el-link type="primary" class="custom-link" :underline="false">{{
                    row[column.prop]
                  }}</el-link>
                </div>
                <div v-else>
                  <div class="custom-link">{{ row[column.prop] }}</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <el-tabs model-value="jgxq">
        <el-tab-pane label="结果详细" name="jgxq" lazy>
          <el-table
            :data="jgxqData.data"
            stripe
            border
            height="100%"
            show-summary
            :summary-method="getSummaries"
            @sort-change="sortChange"
          >
            <el-table-column
              v-for="column in jgxqData.titles"
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :sortable="true"
              show-overflow-tooltip
              resizable
            >
              <template #default="{ row }">
                <div v-if="column.custom">
                  <el-link type="primary" class="custom-link" :underline="false">{{
                    row[column.prop]
                  }}</el-link>
                </div>
                <div v-else>
                  <div class="custom-link">{{ row[column.prop] }}</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .form-box {
    .zzjg {
      font-size: 20px;
      padding-right: 8px;
    }
    .el-form {
      display: flex;
      .el-form-item.dwmcInfo {
        flex: 1;
        width: 100%;
        display: flex;
        .dwmcInfoTitle {
          flex: 5;
        }
        .dwmcInfoButton {
          display: flex;
          flex: 2;
          justify-content: flex-end;
        }
      }
    }
  }
  .table-box {
    flex: 1;
    display: flex;
    height: calc(100% - 52px);
    .el-tabs {
      flex: 1;
      width: 50%;
      height: 100%;
      :deep(.el-tabs__nav) {
        padding: 0 16px;
      }
      &:last-child {
        margin-left: 10px;
      }
    }
  }
  .custom-link {
    width: 100%;
    display: block;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    .el-link__inner {
      display: inline;
    }
  }
}

.button-group {
  display: flex;
  justify-content: flex-end;
  margin-right: 32px;
  margin-bottom: 10px;
}
</style>
